import { isJson } from '@/utils/is.js'
import { useElementBounding, useResizeObserver } from '@vueuse/core'

export const isExternal = path => {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export const getLocalStorage = key => {
  const value = localStorage.getItem(key)
  if (isJson(value)) {
    return JSON.parse(value)
  } else {
    return false
  }
}

export const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

export function setTableScroll(selector) {
  try {
    const extraHeight = 76
    const table = document.querySelector(selector)
    const tHeader = table.querySelector('.ant-table-thead')
    const tBody = table.querySelector('.ant-table-body')
    //表格内容距离顶部的距离
    const { bottom: tHeaderBottom, height: tHeaderHeight } = useElementBounding(tHeader)
    let _tHeaderHeight = tHeaderHeight.value
    //窗体高度-表格内容顶部的高度-表格内容底部的高度
    let tableHeight = `calc(100vh - ${tHeaderBottom.value + extraHeight}px)`
    useResizeObserver(tHeader, entries => {
      const entry = entries[0]
      const { height } = entry.contentRect
      if (_tHeaderHeight === height) return
      _tHeaderHeight = height
      tableHeight = `calc(100vh - ${tHeaderBottom.value + extraHeight}px)`
      if (tBody) tBody.style.height = tableHeight
    })
    return tableHeight
  } catch (e) {
    console.error(e)
  }
}
